﻿using Core.Attributes;
using Core.Base;
using Core.Com;
using Core.Enums;
using Core.Interfaces;
using Reader.BLE.Models;
using Reader.BLE.UserControls;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Net;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using WeifenLuo.WinFormsUI.Docking;

namespace Reader.BLE.Forms
{
    public partial class FrmBLE : DockContentEx
    {

        static RichTextBoxLog _log = null;

        public FrmBLE()
        {
            InitializeComponent();
            _log = new RichTextBoxLog(rtxt);
        }

        public string GetName()
        {
            return "BLE定位";
        }

        private void FrmBLE_Load(object sender, EventArgs e)
        {
            Init();
        }
        void Init()
        {
            try
            {


                var config = InitConfig();
                if (config == null)
                {
                    _log.LogError($"配置文件有误!");
                    return;
                }
                string ip = config.IP;
                this.Text = ip;
                this.TabText = ip;
                this.lblIP.Text = ip;
                listReader.Controls.Clear();
                for (int i = 0; i < 1; i++)
                {
                    ReaderItem item = new ReaderItem(ip, 9999,config.Url, rtxt);
                    this.listReader.Controls.Add(item);
                }
            }
            catch (Exception ex)
            {
                _log.LogError($"程序初始化错误:{ex.Message}");
            }
        }
        private Config InitConfig()
        {
            //读取配置
            try
            {
                var path = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "Iots", "Reader.BLE.json");
                if (!File.Exists(path))
                {
                    _log.LogMessage("Reader.BLE.json文件不存在!");
                    return null;
                }
                else
                {
                    //读取json文件
                    string json = "";
                    using (System.IO.StreamReader sr = new System.IO.StreamReader(path))
                    {
                        json = sr.ReadToEnd();
                    }
                    Config config = json.FromJson<Config>();
                    return config;

                }
            }
            catch (Exception ex)
            {
                _log.LogError($"InitConfig.Error={ex.Message}");
                return null;
            }

        }


        private void btnSetting_Click(object sender, EventArgs e)
        {
            FrmConfig open = new FrmConfig();
            if (open.ShowDialog() == DialogResult.OK)
            {
                Init();
            }
        }
    }
}
